var geocoder;
var map;
var tmpMarker;
var tmpMarkers = [];
var googlemapkey = 'AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM';//'AIzaSyCvXjC9t8o0MDG89LrcAzImA_lcaeSKObs';

/**
 * Initial google map api with id of the dom element in the html
*/
function initMap(div_id) {
   geocoder = new google.maps.Geocoder();
   var latlng = new google.maps.LatLng(0, 0);
   var mapOptions = {
      disableDefaultUI:true,
      disableDoubleClickZoom: true,
      //scrollwheel: false,
      zoom: 12,
      mapTypeId:google.maps.MapTypeId.TERRAIN,   //ROADMAP
      center: latlng
   }
   map = new google.maps.Map(document.getElementById(div_id), mapOptions);
   //google.maps.event.addListener(map, 'click', function(event) {
   //   placeMarker(map, event.latLng);
   //});   
}

/**
 * Return the google.maps.LatLng object from given address
*/
function getGeocodeAddress(str) {
   var address = str;
   geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         //dropMarker(results[0].geometry.location);
         return results[0].geometry.location;
      } else {
         //alert("Geocode was not successful for the following reason: " + status);
         return null;
      }
   });
}

/**
 * Move the google.maps.LatLng location in the map with a marker
*/
function moveMarkerTo(lat, lng){
   //console.log(JSON.stringify(loc));
   //map.setCenter(loc);
   tmpMarker = null;
   tmpMarker = new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(lat, lng)
   });
}

/**
 * Drawing an google.maps.LatLng location on the map
*/
function drawMarker(lat, lng){
   tmpMarkers.push( new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(lat, lng)
   }));
}

/**
 * Drawing an google.maps.LatLng location on the map with info window
*/
function drawMarkerWithContent(lat, lng, dom_msg){
   var infowindow = new google.maps.InfoWindow({
      content: dom_msg
   });
   var mk = new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(lat, lng),
      infowindow: infowindow
   });
   google.maps.event.addListener(mk, 'click', function(event) {
      onMarkerClick(event, mk); 
   });
   infowindow.open(map, mk);
   tmpMarkers.push(mk);
}

/**
 * On Marker Click Event - shows the info window 
 * infowindow obj should be stored with the marker, please check "drawMarkerWithContent"
*/
function onMarkerClick(event, marker) { 
   var infowindow = marker.infowindow; 
   infowindow.open(map, marker);
}

/**
 * Erase all google.maps.LatLng locations on the map
*/
function clearMarkers(){
   for(var i = 0; i < tmpMarkers.length; i++){
      tmpMarkers[i].map = null;
      tmpMarkers[i] = null;
   }
   tmpMarkers = [];
}

/**
 * Centering the map at given google.maps.LatLng location
*/
function centerMap(lat, lng, zoom){
   map.setZoom(zoom);
   map.setCenter(new google.maps.LatLng(lat, lng));
}
